<template>
  <el-card class="box-card">
    <div class="chart">
      <div class="file-count">
        <h3> 每日上传文件数量统计（7 天）</h3>
        <div id="file-count-chart"> </div>
      </div>
      <div class="file-type">
        <h3>文件类型统计</h3>
        <div id="file-type-chart"> </div>
      </div>
    </div>
    <div class="report">
      <h3>统计报表 &ensp; <el-button size="small" @click="handleExport">导出报表</el-button> </h3>
      <table>
        <thead>
          <tr>
            <th colspan="4" class="table-title">文件统计报表</th>
          </tr>
          <tr>
            <th colspan="1">日期</th>
            <th colspan="3">{{ DateUtils.getToday() }}</th>
          </tr>
        </thead>

        <tbody v-if="fileTypeList?.length">
          <tr>
            <th colspan="4">文件数量统计（单位：个）</th>
          </tr>
          <tr>
            <td>今日上传文件数量</td>
            <td>{{ fileCountList!.at(-1)!.count }}</td>
            <td>总文件数量</td>
            <td>{{ totalFileCount }}</td>
          </tr>
          <tr>
            <td>本周上传文件数量</td>
            <td>{{ fileCountAddThisWeek }}</td>
            <td>本月上传文件数量</td>
            <td>{{ fileCountAdd4ThisMonth }}</td>
          </tr>
          <tr>
            <th colspan="4">文件类型统计（单位：个）</th>
          </tr>
          <tr>
            <td>image</td>
            <td>{{ fileTypeList![0].value }}（占比：{{ fileTypeList![0].proportion }} %）</td>
            <td>video</td>
            <td>{{ fileTypeList![1].value }}（占比：{{ fileTypeList![1].proportion }} %）</td>
          </tr>
          <tr>
            <td>word</td>
            <td>{{ fileTypeList![2].value }}（占比：{{ fileTypeList![2].proportion }} %）</td>

            <td>excel</td>
            <td>{{ fileTypeList![3].value }}（占比：{{ fileTypeList![3].proportion }} %）</td>
          </tr>
          <tr>
            <td>ppt</td>
            <td>{{ fileTypeList![4].value }}（占比：{{ fileTypeList![4].proportion }} %）</td>
            <td>markdown</td>
            <td>{{ fileTypeList![5].value }}（占比：{{ fileTypeList![5].proportion }} %）</td>
          </tr>
          <tr>
            <td>txt</td>
            <td>{{ fileTypeList![6].value }}（占比：{{ fileTypeList![6].proportion }} %）</td>
            <td>other</td>
            <td>{{ fileTypeList![7].value }}（占比：{{ fileTypeList![7].proportion }} %）</td>
          </tr>
        </tbody>
      </table>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'
import { computed, onMounted, ref } from 'vue'
import DateUtils from '@/utils/date'
type FileCount = {
  updateTime: string
  count: number
}
type FileType = {
  name: string
  value: number
  proportion: string
}
type Result<T> = {
  code: string
  message: number
  total: number
  data: T[]
}

const fileCountList = ref<FileCount[]>()
// 获取文件数量列表
const getFileCountList = async () => {
  const start = DateUtils.getWeekAgoDate()
  const end = DateUtils.getToday()

  const res = await fetch(
    `http://localhost:8085/dataOverview/getFileCountByDateRange?start=${start}&end=${end}`
  ).then<Result<FileCount>>((res) => res.json())
  fileCountList.value = res.data
}

// 本周上传文件数量
const fileCountAddThisWeek = computed(() =>
  eval(fileCountList.value!.map((item) => item.count).join('+'))
)

const fileTypeList = ref<FileType[]>()
const totalFileCount = ref<number>()
// 获取文件类型统计列表
const getFileTypeList = async () => {
  const res = await fetch('http://localhost:8085/dataOverview/getFileTypeStat').then<
    Result<FileType>
  >((res) => res.json())
  fileTypeList.value = res.data
  totalFileCount.value = res.total
}

// 渲染图表通用方法
const renderChart = (chartId: string, option: EChartsOption) => {
  const chartDom = document.getElementById(chartId)!
  const myChart = echarts.init(chartDom)
  myChart.setOption(option)
  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

// 渲染文件数量统计图
const renderFileCountChart = async () => {
  await getFileCountList()
  const fileCountOption: EChartsOption = {
    tooltip: {
      show: true,
      formatter: '日期：{b}<br /> 数量：{c}'
    },
    xAxis: {
      type: 'category',
      data: fileCountList.value?.map((item) => item.updateTime)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: fileCountList.value?.map((item) => item.count),
        type: 'line',
        smooth: true
      }
    ]
  }

  renderChart('file-count-chart', fileCountOption)
}

// 渲染文件类型统计图
const renderFileTypeChart = async () => {
  await getFileTypeList()
  const fileTypeOption: EChartsOption = {
    title: {
      text: '文件类型统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      valueFormatter: (value) => {
        const proportion = (((value as number) / totalFileCount.value!) * 100).toFixed(2) + '%'
        return `${value}（占比：${proportion}）`
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '文件类型',
        type: 'pie',
        radius: '75%',
        data: fileTypeList.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  renderChart('file-type-chart', fileTypeOption)
}

const fileCountAdd4ThisMonth = ref<number>(0)
// 获取本月新增文件数量
const getFileCountAdd4ThisMonth = async () => {
  const res = await fetch('http://localhost:8085/dataOverview/getFileCountAdd4ThisMonth').then<{
    code: string
    message: number
    data: number
  }>((res) => res.json())
  fileCountAdd4ThisMonth.value = res.data
}
onMounted(() => {
  renderFileCountChart()
  renderFileTypeChart()
  getFileCountAdd4ThisMonth()
})

// 导出报表
const handleExport = () => {
  window.location.href = 'http://localhost:8085/dataOverview/exportExcel'
}
</script>

<style lang="scss" scoped>
.box-card {
  height: 100%;

  :deep(.el-card__body) {
    display: flex;
    height: 95%;
  }

  .chart,
  .report {
    flex: 1;
  }

  .chart {
    .file-count,
    .file-type {
      height: 350px;
    }
    #file-count-chart,
    #file-type-chart {
      width: 100%;
      height: 100%;
    }
  }

  .report {
    table {
      border-collapse: collapse;
      width: 100%;
      .table-title {
        font-size: 20px;
      }
    }
    th,
    td {
      padding: 10px;
      border: 1px solid #999;
      text-align: center;
    }
  }
}
</style>
